package com.pzh.assignment.service.impl;

import com.pzh.assignment.common.bean.vo.MenuVO;
import com.pzh.assignment.entity.Menu;
import com.pzh.assignment.entity.Role;
import com.pzh.assignment.mapper.MenuMapper;
import com.pzh.assignment.service.IMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author pengzhihao
 * @since 2022-04-05
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements IMenuService {

    private Integer ROOT_MENU_ID  = 0;
    private String AUTH_ROUTER = "router";
    private String ROUTER_ROOT = "root";
    private String ROUTER_CHILDREN = "children";

    private HashMap<String, String> authMap = new HashMap<>();

    @Autowired
    MenuMapper menuMapper;

    /**
     * @description: 通过当前角色获取菜单配置
     * @param: role
     * @return: java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
     * @author pengzhihao
     * @date: 2022/4/5
     */
    @Override
    public List<Map<String, Object>> getMenusByRole(Role role) {
        //设置认证信息
        setAuthMap(role);
        List<Menu> menus = menuMapper.findMenusByRoleId(role.getId());
        List<MenuVO> voList = new ArrayList<>();
        //构造路由菜单树
        for (Menu menu : menus) {
            //如果是顶级菜单
            if (menu.getPid() == ROOT_MENU_ID) {
                MenuVO vo = MenuVO.valueOf(menu);
                vo.setAuthority(authMap);
                setChildrenByPid(menu.getId(), vo.getChildren(), menus);
                voList.add(vo);
            }
        }
        HashMap<String, Object> menuMap = new HashMap<>();
        //vue-antd-admin 异步菜单格式要求
        menuMap.put(AUTH_ROUTER, ROUTER_ROOT);
        menuMap.put(ROUTER_CHILDREN, voList);
        List<Map<String, Object>> menuMapList = new ArrayList<>();
        menuMapList.add(menuMap);
        return menuMapList;
    }

    /**
     * @description: 设置vue-antd-admin路由所需认证方式
     * @param: role
     * @return: java.util.Map<java.lang.String,java.lang.String>
     * @author pengzhihao
     * @date: 2022/4/5
     */
    private void setAuthMap(Role role){
        authMap.put("role", role.getName());
    }

    /**
     * @description:  填充子菜单
     * @param: pid  父级菜单id
     * @param: voList   需要填充的集合
     * @param: menuList 角色拥有的所有菜单
     * @return: void
     * @author pengzhihao
     * @date: 2022/4/5
     */
    private void setChildrenByPid(Integer pid, List<MenuVO> voList, List<Menu> menuList) {
        for (Menu menu : menuList) {
            if (menu.getPid() == pid) {
                MenuVO menuVO = MenuVO.valueOf(menu);
                menuVO.setAuthority(authMap);
                voList.add(menuVO);
            }
        }
    }
}
